<template>
  <div class="flex flex-row items-center">
    <template v-if="isTime">
      <a-time-picker
        v-model:value="startTime"
        placeholder="开始时段"
        :disabled="isAll === '1'"
        value-format="HH:mm:ss"
      />
      <a-time-picker v-model:value="endTime" placeholder="结束时段" :disabled="isAll === '1'" value-format="HH:mm:ss" />
    </template>
    <a-range-picker
      v-else
      v-model:value="range"
      :mode="['date', 'date']"
      :value-format="'YYYY-MM-DD'"
      :disabled="isAll === '1'"
    ></a-range-picker>
    <a-radio-group v-model:value="isAll" name="radioGroup" class="!ml-4">
      <a-radio value="1">{{ isTime ? "全天" : "长期" }}</a-radio>
      <a-radio value="0">{{ isTime ? "时段" : "有效期" }}</a-radio>
    </a-radio-group>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from "vue";

const props = defineProps<{
  isTime: boolean;
  value: { range: [string, string]; isAll: boolean } | null;
}>();
const emits = defineEmits(["change"]);

const range = ref<[string, string]>(["", ""]);
const isAll = ref("0");
const startTime = ref("");
const endTime = ref("");

let trigger = true;
watch([range, startTime, endTime, isAll], ([range, startTime, endTime, isAll]) => {
  trigger = false;
  // console.log(startTime, endTime);
  if (props.isTime) {
    if (startTime && endTime && isAll === "0") {
      emits("change", { range: [startTime, endTime], isAll: false });
    } else if (isAll === "1") {
      emits("change", { range: ["", ""], isAll: true });
    } else {
      emits("change", null);
    }
  } else {
    if (range[0] && range[1] && isAll === "0") {
      emits("change", { range, isAll: false });
    } else if (isAll === "1") {
      emits("change", { range: ["", ""], isAll: true });
    } else {
      emits("change", null);
    }
  }
  nextTick(() => {
    trigger = true;
  });
});

watch(
  () => props.value,
  (value) => {
    if (!trigger) return;
    // console.log("========>props.value", value);
    if (value) {
      isAll.value = value.isAll ? "1" : "0";
      startTime.value = value.range[0];
      endTime.value = value.range[1];
      range.value = value.range;
    } else {
      isAll.value = "0";
      startTime.value = "";
      endTime.value = "";
      range.value = ["", ""];
    }
  },
  { immediate: true }
);
</script>
